package cn.ssj.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2017-09-08.
 */
public class UploadUtils {

    public  static String  upload(MultipartFile file,String locationPath,String handlerPath, HttpServletRequest request) {
        try {
            if (file == null) {
                return "error";
            }
            String filename = file.getOriginalFilename();
            //获取图片存储路径
            //String basePath="/upload";
            //String basePath = request.getServletContext().getRealPath("/upload");
            //获取当前日期的日历对象
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            //获取年
            String year = calendar.get(Calendar.YEAR) + "";
            //获取月
            String month = calendar.get(Calendar.MONTH) + 1 + "";
            //获取日
            String day = calendar.get(Calendar.DAY_OF_MONTH) + "";
            String childrenPath=year +"/"+ month +"/"+ day;
            String parentPath = locationPath+"/" + childrenPath;
            File parent = new File(parentPath);
            //文件目录不存在则创建文件目录
            if (!parent.exists()) {
                parent.mkdirs();
            }
            file.transferTo(new File(parentPath, filename));
            return handlerPath+"/"+childrenPath+"/" + filename;
        } catch (IOException e) {
            return "error";
        }
    }
}
